<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js"></script>
    <script src="/js/table.js"></script>
</head>
<body>
    <div>
        <h1>City Page</h1>
        <table id="city-table"></table>
    </div>
    <script>
        var cityColumns=[{title:"id"},{title:"city"},{title:"operation"}];
        $(function(){ //页面加载完成以后执行
            doInit("city-table",cityColumns);//创建thead,tbody
            doLoadCitys();
        })

        function doLoadCitys(){
            $.ajax({
                url:"/doAjaxGet",
                success(result){//readyState==4 && status==200
                    //console.log(result);
                    doSetTableBodyRows($("#city-table>tbody"),result);
                }
            });
        }
        //将服务端响应的结果更新到页面table的tbody位置
        function doSetTableBodyRows(tBody,result){
            //获取tbody对象
            //let tBody=$("#city-table>tbody");
            //清空tbody原有内容
            tBody.empty();
            //迭代服务端的响应结果，并将其追加到tbody

            // for(let i=0;i<result.length;i++){
            //     tBody.append(doCreateRow(result[i]));
            // }

            // result.forEach(function (item) {
            //     tBody.append(doCreateRow(item));
            // })

            result.forEach(item => tBody.append(doCreateRow(item)));
        }
        function doCreateRow(row){
            return `<tr>
                      <td>${row.id}</td>
                      <td>${row.city}</td>
                      <td><a href='javascript:doDeleteById(${row.id})'>delete</a></td>
                   </tr>`
        }

        function doDeleteById(id) {
            $.ajax({
                url:`/doAjaxDelete/${id}`,
                type:"delete",
                success(result) {
                    alert(result);
                    doLoadCitys();
                }
            })
        }

    </script>
</body>
</html>